package datastructure;

import java.util.ArrayList;

public class Grammatica {
	private static Grammatica instance;
	private ArrayList<Rule> bnf;
	
	public static Grammatica getInstance() {
		if(instance == null) {
			instance = new Grammatica();
		}
		return instance;
	}
	
	private Grammatica() {}
	
	public void setBnf(ArrayList<Rule> bnf) {
		this.bnf = bnf;
		checkForDoubles();
	}
	
	public String toString() {
		String s = "";
		for(Rule r : bnf) {
			s += r.toString();
		}
		return s;
	}
	
	private void checkForDoubles() {
		for(int i = 0; i < bnf.size(); i++) {
			Rule ri = bnf.get(i);
			for(int j = i+1; j < bnf.size(); j++) {
				Rule rj = bnf.get(j);
				if(ri.getNonTerminal().equals(rj.getNonTerminal())) {
					ri.getAlternatives().addAll(rj.getAlternatives());
					bnf.remove(j);
					j--;
				}
			}
		}
	}
	
	public void defineStarters() {
		for(Rule r : bnf) {
			r.defineStarters();
		}
	}
	
	public void defineFollowers(){
		for(Rule r : bnf){
			r.defineFollowers();
		}
	}
	
	public Rule findRuleByTerm(NonTerminal nonTerminal) {
		for(Rule r : bnf) {
			if(r.getNonTerminal().equals(nonTerminal)) {
				return r;
			}
		}
		return null;
	}

	public ArrayList<Rule> getBnf() {
		return bnf;
	}
}
